package com.wangshb.upms.generate.generate;

import com.wangshb.upms.generate.Configuration;
import com.wangshb.upms.generate.FreeMarkerTemplateUtils;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Map;

@Slf4j
public abstract class AbstractGenerate implements Generate {

    private Configuration configuration;

    public AbstractGenerate(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public void generate(){
        try {
            generateFileByTemplate(getTemplateName(), getFile(), getTemplateParams());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public abstract File getFile();

    public abstract Map<String, Object> getTemplateParams();

    public abstract String getTemplateName();


    private void generateFileByTemplate(final String templateName, File file, Map<String,Object> dataMap) throws Exception{
        Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
        template.process(dataMap,out);
    }


    public static String replaceUnderLineAndUpperCase(String str, boolean ignoreFirstChar){
        StringBuffer sb = new StringBuffer();
        sb.append(str);
        int count = sb.indexOf("_");
        while(count!=0){
            int num = sb.indexOf("_",count);
            count = num + 1;
            if(num != -1){
                char ss = sb.charAt(count);
                char ia;
                ia = (char) (ss - 32);
                sb.replace(count , count + 1,ia + "");
            }
        }
        String result = sb.toString().replaceAll("_","");
        return ignoreFirstChar ? result : StringUtils.capitalize(result);
    }
}
